import { API_BASE_URL, DEFAULT_API_CONFIG } from './apiConfig';
import { MockService } from './MockService';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { AppConfig } from '../config';
// 定义请求选项接口
export interface RequestOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
  headers?: Record<string, string>;
  body?: any;
  timeout?: number;
  credentials?: 'include' | 'omit' | 'same-origin';
  // 是否需要认证
  requiresAuth?: boolean;
}

// 定义响应接口
export interface HttpResponse<T = any> {
  data: T;
  status: number;
  statusText: string;
  headers: Record<string, string>;
}

// 自定义错误类
export class HttpError extends Error {
  constructor(message: string, public status: number, public data?: any) {
    super(message);
    this.name = 'HttpError';
  }
}

// 判断是否使用axios
const USE_AXIOS = false; // 可通过环境变量配置

// 全局变量存储登录状态
let isLoginModalVisible = false;

// 显示登录模态框的回调函数
let showLoginModalCallback: (() => void) | null = null;

// 设置显示登录模态框的回调函数
export const setShowLoginModalCallback = (callback: () => void) => {
  showLoginModalCallback = callback;
};

// 封装fetch请求
async function fetchRequest<T>(
  url: string,
  options: RequestOptions = {},
): Promise<HttpResponse<T>> {
  // 首先尝试使用MockService拦截请求
  if (MockService.enabled) {
    const mockResponse = await MockService.intercept<T>(url, options);
    if (mockResponse) {
      console.log('Request intercepted by MockService:', url, mockResponse);
      return mockResponse;
    }
  }

  const {
    method = 'GET',
    headers = {},
    body,
    timeout = DEFAULT_API_CONFIG.timeout,
    credentials = 'include',
    requiresAuth = true, // 默认需要认证
  } = options;

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeout);

  try {
    // 构建请求头
    const requestHeaders: Record<string, string> = {
      ...DEFAULT_API_CONFIG.headers,
      ...headers,
    };

    // 如果需要认证，添加token到请求头
    if (requiresAuth) {
      try {
        const storedAuth = await AsyncStorage.getItem(AppConfig.AUTH.TOKEN_KEY);
        if (storedAuth) {
          const { token } = JSON.parse(storedAuth);
          if (token) {
            requestHeaders['Authorization'] = `Bearer ${token}`;
          }
        }
      } catch (error) {
        console.error('Failed to get token from storage', error);
      }
    }

    const config: RequestInit = {
      method,
      headers: requestHeaders,
      credentials,
      signal: controller.signal,
    };

    if (body) {
      if (typeof body === 'object' && !(body instanceof FormData)) {
        config.body = JSON.stringify(body);
      } else {
        config.body = body;
      }
    }

    // 确保URL以/开头或者包含完整协议
    let fullUrl = url;
    if (!url.startsWith('http') && !url.startsWith('/')) {
      fullUrl = `/${url}`;
    }

    if (!url.startsWith('http')) {
      fullUrl = `${API_BASE_URL}${fullUrl}`;
    }

    console.log('Making request to:', fullUrl);

    const response = await fetch(fullUrl, config);

    clearTimeout(timeoutId);

    const responseHeaders: Record<string, string> = {};
    response.headers.forEach((value, key) => {
      responseHeaders[key] = value;
    });

    let data: any;
    const contentType = response.headers.get('content-type');
    if (contentType && contentType.includes('application/json')) {
      data = await response.json();
    } else {
      data = await response.text();
    }

    // 检查是否未认证（401错误）
    if (response.status === 401 && requiresAuth) {
      // 显示登录模态框
      if (showLoginModalCallback && !isLoginModalVisible) {
        isLoginModalVisible = true;
        showLoginModalCallback();
      }
      throw new HttpError('Unauthorized', 401, data);
    }

    if (!response.ok) {
      throw new HttpError(
        data?.message ||
          `HTTP Error: ${response.status} ${response.statusText}`,
        response.status,
        data,
      );
    }

    return {
      data,
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders,
    };
  } catch (error: any) {
    clearTimeout(timeoutId);
    if (error.name === 'AbortError') {
      throw new HttpError('Request timeout', 408);
    }
    throw error;
  }
}

// 如果使用axios
let axiosRequest: <T>(
  url: string,
  options: RequestOptions,
) => Promise<HttpResponse<T>>;

if (USE_AXIOS) {
  // 动态导入axios以减少不必要的依赖
  import('axios')
    .then(axios => {
      const axiosInstance = axios.default.create({
        baseURL: API_BASE_URL,
        timeout: DEFAULT_API_CONFIG.timeout,
        headers: DEFAULT_API_CONFIG.headers,
      });

      // 响应拦截器
      axiosInstance.interceptors.response.use(
        response => response,
        error => {
          const customError = new HttpError(
            error.response?.data?.message || error.message,
            error.response?.status || 500,
            error.response?.data,
          );
          return Promise.reject(customError);
        },
      );

      axiosRequest = async <T>(
        url: string,
        options: RequestOptions,
      ): Promise<HttpResponse<T>> => {
        const {
          method = 'GET',
          headers,
          body,
          timeout,
          requiresAuth = true,
        } = options;

        // 构建请求头
        const requestHeaders: Record<string, string> = {
          ...DEFAULT_API_CONFIG.headers,
          ...headers,
        };

        // 如果需要认证，添加token到请求头
        if (requiresAuth) {
          try {
            const storedAuth = await AsyncStorage.getItem(
              AppConfig.AUTH.TOKEN_KEY,
            );
            if (storedAuth) {
              const { token } = JSON.parse(storedAuth);
              if (token) {
                requestHeaders['Authorization'] = `Bearer ${token}`;
              }
            }
          } catch (error) {
            console.error('Failed to get token from storage', error);
          }
        }

        const config: import('axios').AxiosRequestConfig = {
          url,
          method,
          headers: requestHeaders,
          timeout,
        };

        if (body) {
          config.data = body;
        }

        try {
          const response = await axiosInstance.request(config);
          return {
            data: response.data,
            status: response.status,
            statusText: response.statusText,
            headers: response.headers as Record<string, string>,
          };
        } catch (error: any) {
          // 检查是否未认证（401错误）
          if (error.response?.status === 401 && requiresAuth) {
            // 显示登录模态框
            if (showLoginModalCallback && !isLoginModalVisible) {
              isLoginModalVisible = true;
              showLoginModalCallback();
            }
          }

          throw new HttpError(
            error.response?.data?.message || error.message,
            error.response?.status || 500,
            error.response?.data,
          );
        }
      };
    })
    .catch(() => {
      // 如果axios导入失败，则使用fetch
      axiosRequest = fetchRequest;
    });
}

// 导出统一的请求函数
export async function request<T>(
  url: string,
  options: RequestOptions = {},
): Promise<HttpResponse<T>> {
  if (USE_AXIOS && axiosRequest) {
    return axiosRequest<T>(url, options);
  }
  return fetchRequest<T>(url, options);
}

// 便捷方法
export async function get<T>(
  url: string,
  options: Omit<RequestOptions, 'method' | 'body'> = {},
) {
  return request<T>(url, { ...options, method: 'GET' });
}

export async function post<T>(
  url: string,
  body?: any,
  options: Omit<RequestOptions, 'method' | 'body'> = {},
) {
  return request<T>(url, { ...options, method: 'POST', body });
}

export async function put<T>(
  url: string,
  body?: any,
  options: Omit<RequestOptions, 'method' | 'body'> = {},
) {
  return request<T>(url, { ...options, method: 'PUT', body });
}

export async function patch<T>(
  url: string,
  body?: any,
  options: Omit<RequestOptions, 'method' | 'body'> = {},
) {
  return request<T>(url, { ...options, method: 'PATCH', body });
}

export async function del<T>(
  url: string,
  options: Omit<RequestOptions, 'method' | 'body'> = {},
) {
  return request<T>(url, { ...options, method: 'DELETE' });
}

// 重置登录模态框状态
export const resetLoginModalState = () => {
  isLoginModalVisible = false;
};
